from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import render_template
from flask import request

from info import db
from info.constants import QINIU_DOMIN_PREFIX, USER_COLLECTION_MAX_NEWS, OTHER_NEWS_PAGE_MAX_COUNT, \
    USER_FOLLOWED_MAX_COUNT
from info.models import News, Category, User
from info.utils.common import user_status_monitoring
from info.utils.response_code import RET
from . import user_url
from info.utils.image_storage import *


# 个人中心  其他用户发布的新闻
@user_url.route('/other_news_list')
@user_status_monitoring
def other_news_list():
    page = request.args.get('p', 1)
    user_id = request.args.get("user_id")  # 要查看的其他用的用户id
    if not all([user_id, page]):
        return jsonify(errno=RET.DATAERR, errmsg='数据错误')
    try:
        page = int(page)
        brother = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据错误')
    try:
        paginate = brother.news_list.paginate(page, OTHER_NEWS_PAGE_MAX_COUNT)
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据错误')
    news_list = []
    for item in paginate.items:
        news_list.append(item.to_basic_dict())

    data = {
        'news_li': news_list,
        'total_page': total_page,
        'current_page': current_page,
    }

    return jsonify(errno=RET.OK, errmsg='操作成功', data=data)


# 个人中心  其他用户信息
@user_url.route('/other_user')
@user_status_monitoring
def other_user():
    user = g.user
    user_id = request.args.get("user_id")  # 要查看的其他用的用户id
    if not user_id:
        return render_template('news/other.html', errmsg='参数错误')

    try:
        user_id = int(user_id)
        brother = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return render_template('news/other.html', errmsg='参数错误')

    is_follow = False
    if brother in user.followed:
        is_follow = True

    data = {
        'user': user.to_dict(),
        'brother': brother.to_dict(),
        'is_follow': is_follow
    }
    return render_template('news/other.html', data=data)


# 个人中心  用户的关注列表
@user_url.route('/user_follow')
@user_status_monitoring
def user_follow():
    page = request.args.get('p', 1)
    user = g.user

    if not page:
        return render_template('news/user_follow.html', errmsg='参数错误')
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)

    follow_list = []
    try:
        paginate = user.followed.paginate(page, USER_FOLLOWED_MAX_COUNT)
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
        return render_template('news/user_follow.html', errmsg='数据查询错误')

    for item in paginate.items:
        follow_list.append(item.to_dict())

    data = {
        'total_page': total_page,
        'current_page': current_page,
        'follow_list': follow_list
    }

    return render_template('news/user_follow.html', data=data)


# 个人中心 用户新闻列表
@user_url.route('/news_list')
@user_status_monitoring
def news_list():
    user = g.user
    page = request.args.get('p', 1)  # 获得要显示的页面

    page = int(page)

    paginate = None
    try:
        paginate = user.news_list.paginate(page, 6)
    except Exception as e:
        current_app.logger.error(e)

    current_page = paginate.page
    total_page = paginate.pages

    new_dict_li = []
    for item in paginate.items:
        new_dict_li.append(item.to_review_dict())

    data = {
        'news_list': new_dict_li,
        'current_page': current_page,
        'total_page': total_page,
    }

    return render_template('news/user_news_list.html', data=data)


# 个人中心 用户发表新闻
@user_url.route('/news_release', methods=['get', 'post'])
@user_status_monitoring
def news_release():
    if request.method == 'GET':
        category = None
        try:
            category = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        category.pop(0)
        category_list = []
        for item in category:
            category_list.append(item.to_dict())
        data = {
            'category': category_list
        }
        return render_template('news/user_news_release.html', data=data)

    title = request.form.get('title')  # 新闻标题
    category_id = request.form.get('category_id')  # 新闻分类ID
    source = '个人用户'
    digest = request.form.get('digest')  # 新闻摘要
    index_image = request.files.get('index_image')  # 索引图片
    content = request.form.get('content')  # 新闻内容
    # 参数校验
    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.DATAERR, errmsg='数据错误')
    try:
        file = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据错误')
    # 上传新闻图片
    try:
        key = storage(file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='图片上传错误')

    # 新闻添加到数据库
    new = News()
    new.title = title
    new.source = source
    new.digest = digest
    new.category_id = category_id
    new.content = content
    new.index_image_url = QINIU_DOMIN_PREFIX + key
    new.status = 1
    new.user_id = g.user.id

    try:
        db.session.add(new)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        return jsonify(errno=RET.IOERR, errmsg='新闻发表失败')

    return jsonify(errno=RET.OK, errmsg='新闻发表成功')


# 个人中心 收藏新闻的页面展示
@user_url.route('/collection')
@user_status_monitoring
def collection():
    user = g.user
    page = request.args.get('p', 1)  # 获得要显示的页面

    page = int(page)

    paginate = None
    try:
        paginate = user.collection_news.paginate(page, USER_COLLECTION_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    current_page = paginate.page
    total_page = paginate.pages
    collection_news = []
    for item in paginate.items:
        collection_news.append(item.to_dict())

    data = {
        'collection_news': collection_news,
        'current_page': current_page,
        'total_page': total_page
    }

    return render_template('news/user_collection.html', data=data)


# 个人中心 密码修改系统
@user_url.route('/pass_info', methods=['post', 'get'])
@user_status_monitoring
def pass_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    # 1.获取参数
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')
    # 2.校验参数
    if not all([old_password, new_password]):
        return jsonify(errno=RET.DATAERR, errmsg='数据错误')

    # 密码属性设置为不可读取 ，check_passowrd函数用来直接校验密码
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg='原始密码错误')
    if old_password == new_password:
        return jsonify(errno=RET.PWDERR, errmsg='新密码不能和原始密码一致')
    # 3.修改密码
    user.password = new_password

    return jsonify(errno=RET.OK, errmsg='修改成功')


# 个人中心 头像的管理
@user_url.route('/pic_info', methods=['post', 'get'])
@user_status_monitoring
def pic_info():
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={"user": user.to_dict()})

    # 1.获取参数（读取上传的文献）
    try:
        avatar = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据错误')

    # 使用七牛云吧文件上传至服务器
    try:
        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='图片上传错误')

    user.avatar_url = key

    return jsonify(errno=RET.OK, errmsg='上传成功', data={'avatar_url': QINIU_DOMIN_PREFIX + user.avatar_url})


# 个人中心基本信息设置
@user_url.route('/base_info', methods=['post', 'get'])
@user_status_monitoring
def base_info():
    user = g.user
    if request.method == 'GET':
        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)
    # 1.获取传递过来的参数
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')
    # 2.校验参数
    if not all([nick_name, gender]):
        return jsonify(errno=RET.DATAERR, errmsg='数据错误')
    if gender not in ['MAN', 'WOMEN']:
        return jsonify(errno=RET.DATAERR, errmsg='数据错误')
    # 3.跟新并保存数据
    user.nick_name = nick_name
    user.gender = gender
    if signature:
        user.signature = signature
    return jsonify(errno=RET.OK, errmsg='操作成功')


# 个人中心主页
@user_url.route('/info')
@user_status_monitoring
def user_center():
    user = g.user
    if not user:
        return redirect('/')
    data = {
        'user': user.to_dict()
    }
    return render_template('news/user.html', data=data)
